from PyQt5.QtWidgets import QDialog, QVBoxLayout, QTableWidget, QTableWidgetItem,\
      QPushButton, QCheckBox, QLineEdit, QLabel, QHBoxLayout

from utils.tools import showMessageBox

class EditDialog(QDialog):
    def __init__(self, rows_data, headers, parent=None):
        super().__init__(parent)
        self.setWindowTitle("批量修改")
        self.resize(900, 400)
        self.layout = QVBoxLayout(self)
        self.table = QTableWidget(len(rows_data), len(headers), self)
        self.table.setHorizontalHeaderLabels(headers)

        # 调整列宽
        for i, width in enumerate([50, 225, 50, 50, 75, 250, 100]):
            if i < len(headers):
                self.table.setColumnWidth(i, width)

        for i, row in enumerate(rows_data):
            for j, value in enumerate(row):
                self.table.setItem(i, j, QTableWidgetItem(str(value)))
        self.layout.addWidget(self.table)
        self.print_checkbox = QCheckBox("修改后立即打印", self)
        self.layout.addWidget(self.print_checkbox)

        self.label_id = QLabel("发票ID:", self)
        self.lineEdit_id = QLineEdit(self)
        self.layout_id = QHBoxLayout()
        self.layout_id.addWidget(self.label_id)
        self.layout_id.addWidget(self.lineEdit_id)
        self.layout.addLayout(self.layout_id)

        self.btn_ok = QPushButton("确定", self)
        self.btn_ok.clicked.connect(self.accept)
        self.layout.addWidget(self.btn_ok)

        self.headers = headers
        self.price_col = headers.index("金额")
        self.num_col = headers.index("数量")
        self.unit_price_col = headers.index("单价")
        self.table.cellChanged.connect(self.autoCalcPrice)

    def accept(self):
        if self.print_checkbox.isChecked() and not self.lineEdit_id.text().strip():
            showMessageBox("需要打印请填写发票ID")
            return
        super().accept()

    def getData(self):
        data = []
        for i in range(self.table.rowCount()):
            row = []
            for j in range(self.table.columnCount()):
                row.append(self.table.item(i, j).text())
            data.append(row)
        return data

    def isPrintChecked(self):
        return self.print_checkbox.isChecked()

    def getID(self):
        return self.lineEdit_id.text().strip()

    def autoCalcPrice(self, row, col):
        if col in [self.num_col, self.unit_price_col]:
            try:
                num = float(self.table.item(row, self.num_col).text())
                unit_price = float(self.table.item(row, self.unit_price_col).text())
                price = num * unit_price
                self.table.blockSignals(True)
                self.table.setItem(row, self.price_col, QTableWidgetItem("{:.1f}".format(price)))
                self.table.blockSignals(False)
            except Exception:
                pass  # 可以加错误提示